package ee.ut.cs.mc.madp.p2pdivider.adapter;

import java.util.ArrayList;
import java.util.Arrays;

import android.content.Context;
import android.net.wifi.p2p.WifiP2pDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import ee.ut.cs.mc.madp.p2pdivider.R;
import ee.ut.cs.mc.madp.p2pdivider.fragment.DevicesFragment;

/**
 * Adapter that provides layout and data for device fragment data
 * 
 * @author Kaarel Jõgeva
 */
public class DeviceGridAdapter extends ArrayAdapter<WifiP2pDevice> {

    // private final WifiP2pDevice[] objects;
    private final DevicesFragment fragment;

    public DeviceGridAdapter(Context context, int textViewResourceId, DevicesFragment fragment, WifiP2pDevice[] objects) {
        super(context, textViewResourceId, new ArrayList<WifiP2pDevice>(Arrays.asList(objects)));
        this.fragment = fragment;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) fragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.view_device_grid_cell, null);
        }
        final WifiP2pDevice device = getItem(position);// position < objects.length ? objects[position] : null;
        if (device != null) {
            v.setVisibility(View.VISIBLE);
            ImageButton info = (ImageButton) v.findViewById(R.id.deviceGridInfo);
            TextView tv = (TextView) v.findViewById(R.id.deviceName);
            if (info != null) {
                String name = device.deviceName;
                if (name == null || name.isEmpty()) {
                    name = fragment.getString(R.string.host_device);
                }
                
                tv.setText(name);
            }
        } else {
            v.setVisibility(View.INVISIBLE);
        }

        return v;
    }

}
